package com.jash.lifxdemo;

import android.app.Application;
import android.os.StrictMode;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.jash.lifxdemo.utils.NetService;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.SimpleTimeZone;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class BaseApplication extends Application {
    private NetService service;

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());
        }
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new TypeAdapter<Date>() {
                    private final SimpleDateFormat SDF = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
                    @Override
                    public void write(JsonWriter out, Date value) throws IOException {
                        if (value == null) {
                            out.nullValue();
                        } else {
                            out.value(SDF.format(value));
                        }
                    }

                    @Override
                    public Date read(JsonReader in) throws IOException {
                        if (in.hasNext()) {
                            String s = in.nextString();
                            try {
                                return SDF.parse(s);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                        return null;
                    }
                }).create();
        service = new Retrofit.Builder()
                .baseUrl("http://api.lifxapi.com/")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
                .create(NetService.class);
    }

    public NetService getService() {
        return service;
    }
}
